import Taro, { Component } from '@tarojs/taro'
import {View, Picker, Input} from '@tarojs/components'
import { AtMessage, AtTextarea, AtButton } from 'taro-ui'
import qs from 'qs'
import './index.scss'
import { connect } from '@tarojs/redux'
import {getRealLeaveDay, saveOrUpdateDistributeLeave} from '../service'
import moment from 'moment'

@connect(({ counter }) => ({
  counter
}))
export default class attendance extends Component {

  config = {
    navigationBarTitleText: '零星请假申请'
  };

  constructor (props) {
    super(props);
    this.state = {
      userInfo: props.counter,
      leaveTime: 0,
      formData: {}
    }
  }

  componentDidMount () {
    let array = window.location.hash.split('?');
    if (array.length>1){
      let obj = qs.parse(array[1]);
      let formData = JSON.parse(obj.applyData);
      formData.leaveBeginTime = moment(`${obj.startDate} ${obj.startTime}`);
      formData.leaveEndTime = moment(`${obj.endDate} ${obj.endTime}`);
      this.setState({ formData })
    }
  }

  onPickerChange = (e, key) => {
    const { formData } = this.state;
    let obj = {...formData};
    obj[key] = e.detail.value;
    let verifyKey = ['startDate','startTime','endDate','endTime'];
    if (verifyKey.indexOf(key) > -1 &&  obj.startDate && obj.startTime && obj.endDate && obj.endTime){
      obj.startDate = moment(obj.startDate).format('YYYY-MM-DD');
      obj.endDate = moment(obj.endDate).format('YYYY-MM-DD');
      obj.leaveBeginTime = moment(`${obj.startDate} ${obj.startTime}`);
      obj.leaveEndTime = moment(`${obj.endDate} ${obj.endTime}`);
      let queryData = {type: obj.type, leaveBeginTime: obj.leaveBeginTime, leaveEndTime: obj.leaveEndTime};
      getRealLeaveDay(queryData).then(res => {
        obj.leaveTime = res;
        this.setState({formData: obj})
      })
    }else {
      this.setState({formData: obj})
    }
  };

  onSubmit = () => {
    let { formData, userInfo } = this.state;
    if (!formData.startDate){
      Taro.atMessage({message: '请假开始日期不能为空！', type: 'error'});
      return;
    }else if (!formData.startTime){
      Taro.atMessage({message: '请假开始时间不能为空！', type: 'error'});
      return;
    }else if (!formData.endDate){
      Taro.atMessage({message: '请假结束日期不能为空！', type: 'error'});
      return;
    }else if (!formData.endTime){
      Taro.atMessage({message: '请假结束时间不能为空！', type: 'error'});
      return;
    }else if (!formData.reason){
      Taro.atMessage({message: '请假原因不能为空！', type: 'error'});
      return;
    }
    formData.fileUrl = '';
    let info = {oid: userInfo.oid, name: userInfo.name};
    saveOrUpdateDistributeLeave({ ...formData, ...info }).then(res => {
      if (res.flag){
        Taro.atMessage({message: '保存请假申请成功！', type: 'success'});
        this.onReset();
      }
    })
  };

  onReset () {
    let {formData} = this.state;
    let resetData = {reason: '', leaveTime: null, startDate: null, startTime: null, endDate: null, endTime: null};
    let resetFormData = {...formData, ...resetData};
    this.setState({formData: resetFormData})
  }

  render () {
    let { formData } = this.state;
    return (
      <View className='main-m-t'>
        <AtMessage />
        <View className='fromItem'>
          开始日期：
          <Picker mode='date' className='content-picker'  onChange={(e)=>this.onPickerChange(e,'startDate')}>
            <Input value={formData.startDate} placeholder='请选择开始日期'/>
          </Picker>
        </View>
        <View className='fromItem'>
          开始时间：
          <Picker mode='time' className='content-picker' onChange={(e) => this.onPickerChange(e, 'startTime')}>
            <Input value={formData.startTime} placeholder='请选择开始时间'/>
          </Picker>
        </View>

        <View className='fromItem'>
          结束日期：
          <Picker mode='date' className='content-picker' onChange={(e)=>this.onPickerChange(e,'endDate')}>
            <Input value={formData.endDate} placeholder='请选择结束日期'/>
          </Picker>
        </View>
        <View className='fromItem'>
          结束时间：
          <Picker mode='time' className='content-picker'  onChange={(e)=>this.onPickerChange(e,'endTime')}>
            <Input value={formData.endTime} placeholder='请选择结束时间'/>
          </Picker>
        </View>


        <View className='fromItem' style='align-items: center'>
          时长：
          <View className='content-picker'>
            <Input disabled value={formData.leaveTime}/>
          </View>
        </View>
        <View className='fromItem' style='padding-bottom: 50pt'>
          说明：
          <AtTextarea
            className='content'
            value={formData.reason}
            onChange={(e)=>this.onPickerChange({detail: {value: e}},'reason')}
            maxLength={500}
            placeholder='请输入原因'
          />
        </View>

        <View className='btn-view'>
          <AtButton type='secondary' onClick={this.onReset.bind(this)}>重置</AtButton>
          <AtButton type='primary' onClick={this.onSubmit.bind(this)}>提交</AtButton>
        </View>

      </View>
    )
  }
}
